package com.xy.compose.login.view

import android.annotation.SuppressLint
import androidx.activity.compose.BackHandler
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.aspectRatio
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.pager.HorizontalPager
import androidx.compose.foundation.pager.rememberPagerState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.shadow
import androidx.compose.ui.input.pointer.pointerInput
import androidx.compose.ui.platform.LocalSoftwareKeyboardController
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.input.TextFieldValue
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.hilt.navigation.compose.hiltViewModel
import com.xy.compose.login.viewmodel.LoginViewModel
import com.xy.compose.nav.routes.MainRouter
import com.xy.compose.resource_libs.FontBlackColor
import com.xy.compose.resource_libs.FontWhiteColor
import com.xy.compose.resource_libs.ThemeBackground
import kotlinx.coroutines.launch
import com.xy.compose.resource_libs.R
import com.xy.compose.resource_libs.ThemeButtonBackground
import com.xy.compose.resource_libs.ThemeButtonFocusBackgroundColor
import com.xy.compose.resource_libs.ThemeButtonUnBackgroundColor
import com.xy.compose.resource_libs.ThemeColor
import com.xy.compose.resource_libs.ThemeShawColor

@SuppressLint("RememberReturnType")
@Composable
fun LoginRoute(viewModel: LoginViewModel = hiltViewModel()) {
    val pagerState = rememberPagerState { 4 }
    val scope = rememberCoroutineScope()
    val keyboardController = LocalSoftwareKeyboardController.current

    @Composable
    fun createScrollAction(
        targetPage: Int,
    ): () -> Unit {
        return remember(scope, pagerState, targetPage, keyboardController) {
            {
                keyboardController?.hide()
                scope.launch {
                    pagerState.animateScrollToPage(targetPage)
                }
            }
        }
    }

    BackHandler {
        //出发回退
        if (pagerState.currentPage > 0) {
            scope.launch { pagerState.animateScrollToPage(pagerState.currentPage - 1) }
        }
    }

    HorizontalPager(
        state = pagerState,
        modifier = Modifier
            .fillMaxSize()
            .pointerInput(Unit) {
                awaitPointerEventScope {
                    // 替代方案：遍历所有触摸点并消费事件
                    while (true) {
                        val event = awaitPointerEvent()
                        event.changes.forEach { it.consume() }
                    }
                }
            }
    ) { page ->
        when (page) {
            0 -> LoginMainBody(loginClick = createScrollAction(targetPage = 1))

            1 -> LoginSignBody(
                backClick = createScrollAction(targetPage = 0),
                confirmClick = createScrollAction(targetPage = 2)
            )

            2 -> LoginVerifyBody(
                backClick = createScrollAction(targetPage = 1),
                confirmClick = createScrollAction(targetPage = 3)
            )

            3 -> LoginQuestionBody(
                backClick = createScrollAction(targetPage = 2),
                confirmClick = {
                    keyboardController?.hide()
                    viewModel.toPageAndCloseCurrent(MainRouter.MAIN_PAGE, MainRouter.LOGIN_PAGE)
                }
            )
        }
    }
}


@Composable
fun LoginMainBody(loginClick: (() -> Unit)) {
    Box(
        modifier = Modifier
            .fillMaxSize()
            .background(ThemeBackground)
    ) {

        Image(
            modifier = Modifier
                .padding(top = 123.dp)
                .fillMaxWidth()
                .aspectRatio(414f / 490f)
                .align(alignment = Alignment.TopCenter),
            painter = painterResource(R.mipmap.icon_login_theme),
            contentDescription = ""
        )

        Text(
            "Start the journey",
            modifier = Modifier
                .padding(start = 66.dp, end = 66.dp, bottom = 104.dp)
                .align(alignment = Alignment.BottomCenter)
                .fillMaxWidth()
                .background(
                    ThemeButtonBackground,
                    RoundedCornerShape(50.dp)
                )
                .padding(vertical = 17.dp)
                .shadow(
                    elevation = 4.dp, // 阴影高度，值越大阴影越明显
                    shape = RoundedCornerShape(50.dp), // 阴影形状需与背景形状一致
                    ambientColor = ThemeShawColor, // 环境光阴影颜色（对应原XML的shadowColor）
                    spotColor = ThemeShawColor // 点光源阴影颜色（与环境光保持一致）
                )
                .clickable(enabled = true, onClick = loginClick),
            textAlign = TextAlign.Center, color = ThemeColor, fontSize = 20.sp,
        )

        Image(
            modifier = Modifier
                .padding(bottom = 20.dp)
                .size(172.dp, 70.dp)
                .align(alignment = Alignment.BottomCenter),
            painter = painterResource(R.mipmap.icon_launcher_bottom),
            contentDescription = ""
        )
    }

}


@Composable
fun LoginSignBody(backClick: (() -> Unit), confirmClick: (() -> Unit)) {
    // 1. 在父组件中管理输入状态
    var usernameState by remember { mutableStateOf(TextFieldValue("")) }
    var passwordState by remember { mutableStateOf(TextFieldValue("")) }

    // 2. 判断是否有输入（用户名和密码都不为空）
    val hasInput = usernameState.text.isNotEmpty() && passwordState.text.isNotEmpty()

    // 3. 根据输入状态设置按钮样式
    val confirmBackgroundColor = if (hasInput) {
        ThemeButtonFocusBackgroundColor // 有输入时的颜色
    } else {
        ThemeButtonUnBackgroundColor // 默认颜色
    }
    val fontColor = if (hasInput) {
        FontBlackColor
    } else {
        FontWhiteColor
    }

    Column(
        modifier = Modifier
            .fillMaxSize()
            .background(ThemeBackground)
            .padding(top = 60.dp)
    ) {
        LoginTop(
            confirmBackground = confirmBackgroundColor,
            fontColor = fontColor,
            confirmClickable = hasInput,
            backClick = backClick,
            confirmClick = confirmClick
        )
        Text(
            "Sign in to your organization",
            modifier = Modifier.padding(start = 20.dp, end = 20.dp, top = 12.dp),
            textAlign = TextAlign.Start, color = FontBlackColor, fontSize = 30.sp,
        )
        SignEditor(
            usernameState,
            onUsernameChange = { usernameState = it },
            passwordState,
            onPasswordChange = { passwordState = it })
    }
}

@Composable
fun LoginVerifyBody(backClick: (() -> Unit), confirmClick: (() -> Unit)) {
    // 1. 在父组件中管理输入状态
    var schoolState by remember { mutableStateOf(TextFieldValue("")) }

    // 2. 判断是否有输入（用户名和密码都不为空）
    val hasInput = schoolState.text.isNotEmpty()

    // 3. 根据输入状态设置按钮样式
    val confirmBackgroundColor = if (hasInput) {
        ThemeButtonFocusBackgroundColor // 有输入时的颜色
    } else {
        ThemeButtonUnBackgroundColor // 默认颜色
    }
    val fontColor = if (hasInput) {
        FontBlackColor
    } else {
        FontWhiteColor
    }
    Column(
        modifier = Modifier
            .fillMaxSize()
            .background(ThemeBackground)
            .padding(top = 60.dp)
    ) {
        LoginTop(
            confirmBackground = confirmBackgroundColor,
            fontColor = fontColor,
            confirmClickable = hasInput,
            backClick = backClick,
            confirmClick = confirmClick
        )

        Text(
            "Let’s verify your identity",
            modifier = Modifier.padding(start = 20.dp, end = 20.dp, top = 12.dp),
            textAlign = TextAlign.Start, color = FontBlackColor, fontSize = 30.sp,
        )
        ImageBackgroundInput(
            top = 49.dp,
            title = "Where is your first school?",
            schoolState,
            onTextChange = { schoolState = it })
    }

}

@Composable
fun LoginQuestionBody(backClick: (() -> Unit), confirmClick: (() -> Unit)) {
    // 1. 在父组件中管理输入状态
    var questionState by remember { mutableStateOf(TextFieldValue("")) }

    // 2. 判断是否有输入
    val hasInput = questionState.text.isNotEmpty()

    // 3. 根据输入状态设置按钮样式
    val confirmBackgroundColor = if (hasInput) {
        ThemeButtonFocusBackgroundColor // 有输入时的颜色
    } else {
        ThemeButtonUnBackgroundColor // 默认颜色
    }
    val fontColor = if (hasInput) {
        FontBlackColor
    } else {
        FontWhiteColor
    }

    Column(
        modifier = Modifier
            .fillMaxSize()
            .background(ThemeBackground)
            .padding(top = 60.dp)
    ) {
        LoginTop(
            confirmBackground = confirmBackgroundColor,
            fontColor = fontColor,
            confirmClickable = hasInput,
            backClick = backClick,
            confirmClick = confirmClick
        )

        Text(
            "Almost there, one more question",
            modifier = Modifier.padding(start = 20.dp, end = 20.dp, top = 12.dp),
            textAlign = TextAlign.Start, color = FontBlackColor, fontSize = 30.sp,
        )

        ImageBackgroundInput(
            top = 49.dp,
            title = "When was our 1st release?",
            questionState,
            onTextChange = { questionState = it })
    }

}